<?php

namespace app\api\controller;

use addons\shopro\library\activity\traits\GiveGift;
use app\admin\model\activity\Eventinvite;
use app\admin\model\activityone\EventInviteLogs;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Request;
use app\admin\model\User as UserModel;

/**
 * 首页接口
 */
class Index extends Api
{
    use GiveGift;
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

     /**
     * 拉新活动列表
     */

     public function laxinlist(){
        $laxin = Db::name('event_invite')->order('id desc')->select();
        $this->success('获取成功',$laxin);
     }

     /**
     * 跑步活动列表
     */
    public function runninglist(){
        $runninglist = Db::name('event_checkin')->order('id desc')->select();
        $this->success('获取成功',$runninglist);

    }

    /**
     * 获取队伍列表
     */
    public function teamslist(){
        $id = input('param.id');
        $res = Db::name('event_guess_teams')->where('guess_id',$id)->select();
        $this->success('获取成功',$res);
    }

    /**
     * 竞猜活动接口
     */
    public function eventsguess(){
        $eventlist = Db::name('events_guess')->order('id desc')->select();
    //         echo "<pre>";
    //    print_r($eventlist);die;
        $this->success('获取成功',$eventlist);
    }

    public function eventsguessuser(){
        //用户id
       $res['user_id'] = input('param.userid');
       //活动id
       $res['event_id'] = input('param.eventid');
       //参与时间
       $res['participation_time'] = date("Y-m-d H:i:s");
       //选择的参加的队伍
       $res['team_id'] = input('param.teamid');

    //    $res['team_id'] = explode(',',$res['teamid']);
    //    echo "<pre>";
    //    print_r($res);die;
       //参加的活动id
       $res['guess_id'] = input('param.guessid');
       $result = Db::name('event_guess_user')->insert($res);
       if($result){
         $this->success('选择成功',$result);
       }else{
         $this->error('选择失败');
       }
    }




    /**
     * 查询用户选择的详情
     */
    public function userdetail(){
        $res['user_id'] = input('param.userid');
        $res['event_id'] = input('param.eventid');
        $result = Db::name('event_guess_user')->where($res)->find();
        if($result){
            $this->success('选择成功',$result);
          }else{
            $this->error('选择失败');
          }
    }


    //查询会员等级
    public function leverlist()
    {
        // $userid = input('param.userid');
        // $query = "select level_id,level_name, f.price, if(level_id> 
        // (select level from fa_user where id=:id),true,false) as can_pay
        //  from fa_user_level f order by level_id;";

        //  $userList = Db::query($query, ['id' => $userid]);
        //  echo "<pre>";
        //  print_r($userList);die;


        $userid = $this->auth->id;

        if (empty($userid)) {
            $this->error('参数错误');
        }

      

        $user = Db::name('user')
            ->where('id', $userid)
            ->find();
        if (empty($user)) {
            $this->error('用户不存在');
        }

        $userList = Db::name('user_level')
            ->order('level asc')
            ->select();

        $level = Db::name('user_level')
            ->where('id', $user['level'])
            ->value('level');

        foreach ($userList as $k => &$v) {
            if ($v['level'] <= $level) {
                $v['can_pay'] = 0;
            } else {
                $v['can_pay'] = 1;
            }
        }

        $this->success('请求成功', $userList);
    }

    //查询购买会员
    // public function lever(){
    //     $userlever = Db::name('user_level')->order('level_id desc')->select();
    //     $this->success('请求成功',['code'=>1,'data'=>$userlever]);
    // }


    //查询活动和参加的队伍
    public function activity()
    {
        $user = auth_user();
        $userid = $user->id;

        $activitylist = Db::name('events')->order('id desc')->select();
        $eventlist = array();
        foreach ($activitylist as $k => $v) {
            $v['duiwu'] = Db::name('event_teams')->where('event_id =' . $v['id'])
                ->order('id desc')->select();

            $v['user_select'] =   Db::name('event_user')->where('user_id', $userid)->where('event_id', $v['id'])->find();
            array_push($eventlist, $v);
        }
        $this->success('请求成功', $eventlist);
    }

    public function addvictory()
    {
        $map['user_id'] = input('param.user_id');
        $map['event_id'] = input('param.event_id');
        $map['team_id'] = input('param.team_id');
        $userlever = Db::name('user')->where('id', $map['user_id'])->find();
        if ($userlever['level'] == 0) {
            $this->success('你不是会员，不能参加活动');
        }
        // $map['participation_time'] = time();
        $res = Db::name('event_user')->insert($map);
        if ($res) {
            $this->success('请求成功');
        } else {
            $this->success('请求失败');
        }
    }


    public function couponlist(){
        $where = 'discount';
        $res = Db::name('shopro_coupon')->where('type',$where)->select();
        $this->success('请求成功',$res);
    }

    //上传视频图片接口

    public function upload(){
        $file = $_FILES['file'];
        if ($file['error'] === UPLOAD_ERR_OK) {
            $tmpFilePath = $file['tmp_name'];
            $fileName = $file['name'];
            $targetDir = 'uploads/';
            $targetPath = $targetDir . $fileName;
            move_uploaded_file($tmpFilePath,$targetPath);
            } else {
                echo "文件上传失败！";
            }
        $map['checkin_id'] = input('param.checkinid');
        $map['user_id'] = input('param.userid');
        $map['event_id'] = input('param.eventid');
        $map['checkin_type'] = input('param.checkin_type');
        $map['date'] = date('Y-m-d H:i:s', time());
        $map['status'] = 1;
        $map['created_at'] = date('Y-m-d H:i:s', time());


        if($map['checkin_type'] == 1){
            $map['image'] = '/'.$targetPath;
        }else if($map['checkin_type'] == 2){
            $map['videoimage'] = '/'.$targetPath;
        }
        // $checkModel = Db::name('event_checkin_user')->where('checkin_id',input('param.checkinid'))->find();
        // if($checkModel)
        // {
        //     $number=0;
        //     if($checkModel['numb'])
        //     {
        //         $number=$number+intval($checkModel['numb']);
        //     }
        //     $map['numb']=  $number;
        // }
        // else
        // {
        // }
        $map['numb']= 1;
        $res = Db::name('event_checkin_user')->insert($map);
        if($res){
            $this->success('请求成功',$res);
        } else {
            $this->error('请求失败');
        }
    }

    //会员升级
    public function UpgradeMember()
    {
       $mobile = input('param.mobile');
       $level = input('param.level');
       
    }
    //打卡状态接口

    /**
     * @param Request $request
     * 分享拉新活动
     */
    public function event_laxin(Request $request){
        try {
//            $user = auth_user();
            $user = $this->auth;
            if (!$user->check()){
                throw new Exception('请登录');
            }
            $userid = $user->id;
            $share_user_id = $request->param('user_id');   //分享的用户
            $eventid = $request->param('event_id');        //分享的活动id
            $eventinfo = Eventinvite::where('id','=',$eventid)->find();
            $eventinfo->gift = $eventinfo->gift_coupon;   //重置gift 属性
            $limitdays = date('Y-m-d', strtotime("-{$eventinfo['limit_days']} days"));

            $exites = EventInviteLogs::where([
                'user_id'  => $userid,
                'share_user_id'  => $share_user_id,
                'event_invite_id'  => $eventid,
                ])->count();
            //判断是否已经邀请过
            if ($exites){
                $this->success('请求成功');
            }
            $Createdata = [
                'user_id'  => $userid,
                'share_user_id'  => $share_user_id,
                'event_invite_id'  => $eventid,
                'created_at'  => date("Y-m-d H:i:s"),
                'update_at'  => date("Y-m-d H:i:s"),
            ];
            $logs = EventInviteLogs::create($Createdata);

            /**
             * 获取用户拉新数量
             */
            $laxincount = EventInviteLogs::where('created_at','>=',$limitdays)
                ->where([
                    'share_user_id'=>$share_user_id,
                    'event_invite_id'=>$eventid,
                ])
                ->count();
            //如果拉新用户满足条件就赠送优惠券
            if ($laxincount == $eventinfo['user_count_threshold']){
                $this->giveCoupons($user,$eventinfo->gift_coupon);
            }

            $this->success('请求成功',$logs);
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }
    //查询会员等级以及送的券

    public function levellist(){
        $userviplever = input('param.user_vip_lever');
        $userlevel = Db::name('user_level')->where('level',$userviplever)->find();
        $userlevelcoupon = explode(',',$userlevel['gift_coupon']);
        $coupon = Db::name('shopro_coupon')->where('id','in',$userlevelcoupon)->select();
        $this->success('请求成功',$coupon);
    }

    public function leveladd(){
        $phone = trim(input('param.phone')); 
        $map['level'] = input('param.user_vip_lever'); 
        $userlevel = Db::name('user_level')->where('level',$map['level'])->find();
        //查询用户的numb
        $usernumb = Db::name('user')->where('mobile ='.$phone)->find();
        $map['numb']  = $userlevel['numb']+$usernumb['numb'];
        $userlist = Db::name('user')->where('mobile ='.$phone)->update($map);

        $rows = (new UserModel())->where('mobile ='.$phone)->find();
        if($rows){
            $this->giveCouponsNohidden($rows,$userlevel['gift_coupon']);
        }

    }


    public function updatestatus(){
        $orderid  = input('param.orderid'); 
        $res['status'] = 'unpaid';
        $row = Db::name('shopro_order')->where('id',$orderid)->update($res);
        if($row){
            $this->success('请求成功',$row);    
        }
    }



}
